package netbayServlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import netbay.NetbayUtility;
import netbay.TransactionManager;
import netbay.UserManager;

import util.String.StringUtil;
import util.jQgrid.JQGridFormatterUtil;
import util.jQueryForm.jQueryFormFormatterUtil;
import util.jQueryForm.Ddl.jQueryFormDdl;

/**
 * Servlet implementation class AddAdminServlet
 */
public class AddAdminServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	public static String superAdmin;
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AddAdminServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
    public void init() {
		String configPath = getServletContext().getRealPath(
				"/WEB-INF/config.properties");
		NetbayUtility.init(configPath);
	}
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");  // ensures that user input is interpreted as // 8-bit Unicode (e.g., for Czech characters)
        response.setContentType("text/json;charset=utf-8");
        HttpSession session = request.getSession();
        String url = "";
        String userId = ((!StringUtil.isNullOrEmpty((String)(session.getAttribute("userId")))) ? (String)session.getAttribute("userId"): "null");
        if(!(userId.equals("null"))){
        	url = "/AddAdmin.jsp";
        }
        else{
        	url = "/Login.jsp";
        }
        try{
        	request.getRequestDispatcher(url).forward(request, response);
		} catch (Exception ex) {
            ex.printStackTrace();
        }
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		 	request.setCharacterEncoding("UTF-8");  // ensures that user input is interpreted as // 8-bit Unicode (e.g., for Czech characters)
	        String userPath = request.getServletPath();
	        response.setContentType("application/json;charset=utf-8");
	        PrintWriter out = response.getWriter();
	        HttpSession session = request.getSession();
	        String strJson = "{}";
	        UserManager um = new UserManager();
	        
	        if (userPath.equals("/AddAdminServlet/CheckUsername")) {
	        	String username = (!StringUtil.isNullOrEmpty(request.getParameter("username"))) ? request.getParameter("username").trim() : "";
	        	boolean result = false;
	        	if(username.equals(superAdmin)){
	        		result = false;
	        	}else{
	   		 		result = um.checkUsername(username);
	        	}
	   		 	if(result){
	   		 		strJson = "{\"success\": \"\"}";
	   		 	}else{
	   		 	strJson = "{\"error\": \"Cannot check name of user.\"}";
	   		 	}
	   		 	out.println(strJson);
	        }else if (userPath.equals("/AddAdminServlet/AddNewUser")) {
	        	try {
		        	Integer id ;
		        	String username = (!StringUtil.isNullOrEmpty(request.getParameter("username"))) ? request.getParameter("username").trim() : "";
			        String password = (!StringUtil.isNullOrEmpty(request.getParameter("password"))) ? request.getParameter("password").trim() : "";
			        Integer group = Integer.parseInt((!StringUtil.isNullOrEmpty(request.getParameter("ddlGroup"))) ? request.getParameter("ddlGroup").trim() : "");
			        String rdoRecordType = (!StringUtil.isNullOrEmpty(request.getParameter("rdoRecordType"))) ? request.getParameter("rdoRecordType").trim() : "";
			        String firstname = (!StringUtil.isNullOrEmpty(request.getParameter("firstname"))) ? request.getParameter("firstname").trim() : "";
			        String lastname = (!StringUtil.isNullOrEmpty(request.getParameter("lastname"))) ? request.getParameter("lastname").trim() : "";
			        String address = (!StringUtil.isNullOrEmpty(request.getParameter("address"))) ? request.getParameter("address").trim() : "";
			        String tel = (!StringUtil.isNullOrEmpty(request.getParameter("tel"))) ? request.getParameter("tel").trim() : "";
			        String fax = (!StringUtil.isNullOrEmpty(request.getParameter("fax"))) ? request.getParameter("fax").trim() : "";
			        String email = (!StringUtil.isNullOrEmpty(request.getParameter("mail"))) ? request.getParameter("mail").trim() : "";     
			        String hashPassword = UserManager.hashPassword(password);
			        boolean result = false;
			        
		   		 	result = um.addNewUser(username, hashPassword, group, rdoRecordType, firstname, lastname, address, tel, fax, email);
		   		 	if(result){
						um.saveLog((String)session.getAttribute("userId"),UserManager.actionAddNewUser,username);
	   		 			strJson = "{\"success\": \"\"}";
		   		 	}else{
		   		 	strJson = "{\"error\": \"Cannot add new user.\"}";
		   		 	}
	        	} catch (Exception ex) {
	        		strJson = "{\"error\": \"" + ex.getMessage() + "\"}" ;
				}
	   		 	out.println(strJson);
	   		 	
	        }else if (userPath.equals("/AddAdminServlet/LoadDdl")){
	        	try {
		        	ArrayList<String> result =new ArrayList<String>();
		   		 	result = um.loadDdlGroup();
		   		 	List<jQueryFormDdl> mapDdl = null;
			   		
			        jQueryFormDdl ddl = null;
			        jQueryFormFormatterUtil objJQueryFormFormatterUtil = null;
			       
			        List<Map<String, String>> lValue = new ArrayList();
			       
			        if(result.size()!=0){
			        	mapDdl = new ArrayList<jQueryFormDdl>();
			        	ddl = new jQueryFormDdl("#ddlGroup", "");
				        for(int i = 0;i<result.size();i=i+2){
				        	 Map<String, String> objValue = new HashMap<String,String>();
				        	 objValue.put(result.get(i), result.get(i+1));
				        	 lValue.add(objValue);
				        }	
				        ddl.setValue(lValue);
				        mapDdl.add(ddl);
				        objJQueryFormFormatterUtil = new jQueryFormFormatterUtil();
		            
						strJson = objJQueryFormFormatterUtil.setDdl(mapDdl).buildJson();
			        }
		        } catch (Exception ex) {
		        	strJson = "{\"error\": \"Cannot load data.\"}" ;
				}
				out.println(strJson); 
	        }
		}
	}
